package com.zrj.gateway.filter;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 自定义局部过滤器修改请求体或响应体
 * 可以自定义局部过滤器对某个路由进行过滤，修改请求体或响应体。
 * 自定义局部过滤器需要继承AbstractGatewayFilterFactory，apply方法返回GatewayFilter。
 * 我们需要自定义一个GatewayFilter类，来实现修改请求体或响应体，具体实现跟上面的全局过滤器是一样的。
 * <p>
 * 配置方式
 * filters:
 * - ModifyRequestBody  #注意：ModifyRequestBodyGatewayFilterFactory ，只需要写ModifyRequestBody
 *
 * @author zrj
 * @since 2022/10/7
 **/
@Slf4j
@Component
public class MarkingFilterFactory extends AbstractGatewayFilterFactory {
    @Override
    public GatewayFilter apply(Object config) {
        return new ModifyRequestBodyGatewayFilter();
    }

    class ModifyRequestBodyGatewayFilter implements GatewayFilter, Ordered {

        @Override
        public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
            log.info( "自定义局部过滤器，请求接口：{}", JSONUtil.toJsonStr( exchange.getRequest() ) );
            return chain.filter( exchange );
        }

        @Override
        public int getOrder() {
            return -20;
        }
    }
}
